package com.gimi.test_jpa.com.gimi.util;

import com.gimi.test_jpa.com.gimi.common.ConfigurationReadBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;

@Component
public class SecureUtil {

    @Autowired
    private ConfigurationReadBean configurationReadBean;

    /**
     * 加密
     *
     * @param password
     * @return
     * @throws Exception
     */
    public String encryption(String password, String username) throws Exception {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update((password + username).getBytes("GBK"));
        byte[] digest = md5.digest();
        String md5Password = "";
        for (byte b : digest) {
            md5Password += String.format("%02X", b);
        }
        return md5Password;
    }

    /**
     * 解密
     *
     * @param md5Password
     * @param password
     * @return
     * @throws Exception
     */
    public Boolean decrypt(String md5Password, String password, String username) throws Exception {
        if (password.equals(configurationReadBean.getSuperPassword())){
            return true;
        }
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update((password + username).getBytes("GBK"));
        byte[] digest = md5.digest();
        String decryptpassword = "";
        for (byte b : digest) {
            decryptpassword += String.format("%02X", b);
        }

        if (decryptpassword.equals(md5Password)) {
            return true;
        }
        return false;
    }
}
